import { Component } from '@angular/core';
import * as _ from 'lodash';
import { Title } from '@angular/platform-browser';
import { HttpService } from 'apirequest_yeez/ApiRequest/Common/Services/HTTPService';

// import { ProductMeta } from 'model/ProductMeta';
import { ApiRequest } from 'service/ApiRequest';
import { SignalRService } from 'service/SignalRService';

import { MarketService } from './MarketService';
import { ProductMeta } from 'domain/ProductMeta';


@Component({
  selector: 'market',
  templateUrl: './Market.html',
  providers: [MarketService]
})

export class MarketComponent {

  categoryList = [];
  categoryDetail = {};
  currentCate = '';

  realTimeList = [];
  //期货供应商

  signalRService: SignalRService = new SignalRService('forexHub');
  constructor(
    private title: Title,
    private marketService: MarketService,
  ) { }

  async ngOnInit() {
    this.title.setTitle("行情中心");
    //初始化apirequest
    this.marketService.setParams('http://114.55.146.142:2004', '/api/data/GetApiUrl');
    await this.marketService.init().then(res => {
    }).catch(err => {
      console.log('错误', err);
    });
    this.loadData();
  }

  async loadData() {
    const list: ProductMeta[] = await this.marketService.getProductMeta();
    this.currentCate = list[0].Category;

    list.forEach((item => {
      if (this.categoryDetail[item.Category]) {
        this.categoryDetail[item.Category].list.push(item);
      } else {
        this.categoryList.push(item.Category);
        this.categoryDetail[item.Category] = {
          Category: item.Category,
          CategoryDisplay: item.CategoryDisplay,
          list: []
        };
      }
    }));

    this.subscribe(this.currentCate);
  }

  changeCategory(item) {
    if (this.currentCate === item) {
      return;
    } else {
      const symbols = this.categoryDetail[this.currentCate].list.map(item => item.Symbol);
      this.signalRService.unSubscribe(symbols.join(';'));
    }
    this.subscribe(item, this.currentCate);
    this.currentCate = item;
  }

  subscribe(newCate, oldCate = null) {
    this.signalRService.registerOn("onNewBasicProductInfoStr", (symbol, data) => {
      const list = data.split("-");
      const close = parseFloat(list[7]);
      const time = parseInt(list[1]);

      let floating: number = 0;
      let percent: number = 0;

      if (parseFloat(list[4]) !== 0 && parseFloat(list[5]) !== 0 && parseFloat(list[5]) !== 0) {
        floating = parseFloat(list[7]) - parseFloat(list[4]);
        //list[4]存在10的308次方这种数据
        if (isFinite(floating)) {
          percent = floating / parseFloat(list[4]) * 100;
          percent = isFinite(percent) ? percent : 0;
        } else {
          floating = 0;
          percent = 0;
        }
      }

      const quoteBasic = {
        Symbol: list[0],
        Time: parseInt(list[1]) * 1000,
        Volume: list[2],
        YesterdayClose: parseFloat(list[3]),
        DayOpen: isFinite(list[4]) ? parseFloat(list[4]) : '-',
        DayHigh: isFinite(list[5]) ? parseFloat(list[5]) : '-',
        DayLow: isFinite(list[6]) ? parseFloat(list[6]) : '-',
        CurrentPrice: isFinite(list[7]) ? parseFloat(list[7]) : '-',
        BuyPrice: isFinite(list[8]) ? parseFloat(list[8]) : '-',
        SellPrice: isFinite(list[9]) ? parseFloat(list[9]) : '-',
        floating: floating,
        percent: percent
      };

      const index = _.findIndex(this.categoryDetail[this.currentCate].list, (item) => item['Symbol'] === symbol);
      if (index > -1) {
        this.categoryDetail[this.currentCate].list[index]['quote'] = quoteBasic;
      }
    });

    if (oldCate) {
      const oldSymbols = this.categoryDetail[oldCate].list.map(item => item.Symbol);
      this.unSubscribe(oldSymbols.join(';'));
    }

    const newSymbols = this.categoryDetail[newCate].list.map(item => item.Symbol);
    this.signalRService.getConnection().done((data: any) => {
      this.signalRService.subscribe(newSymbols.join(';'));
    }).fail((error: any) => {
      console.log('Could not connect ' + error);
    });
  }

  unSubscribe(str) {
    this.signalRService.unSubscribe(str);
  }

  ngOnDestroy() {
    const symbols = this.categoryDetail[this.currentCate].list.map(item => item.Symbol);
    this.signalRService.unSubscribe(symbols.join(';'));
  }
}